package com.bilibili.juc.cf;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

public class FutureTaskDemo {
    public static void main(String[] args) throws Exception {
        //固定大小线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        FutureTask<String> futureTask1 = new FutureTask<>(() -> {
            TimeUnit.MICROSECONDS.sleep(500);
            return "callable1";
        });
        threadPool.submit(futureTask1);
        FutureTask<String> futureTask2 = new FutureTask<>(() -> {
            TimeUnit.SECONDS.sleep(3);
            return "callable2";
        });
        threadPool.submit(futureTask2);
//获取异步任务执行结果
        while (true) {
            if (futureTask1.isDone()) {
                System.out.println("futureTask1==>> " + futureTask1.get());
                break;
            }
        }
        System.out.println("futureTask2==>> " + futureTask2.get(2, TimeUnit.SECONDS));
//关闭线程池
        threadPool.shutdown();
    }
}
